package com.hb.trade.api.routine.controller.center.au;

import cn.hutool.json.JSONObject;
import com.hb.core.pojo.center.au.dto.*;
import com.hb.core.pojo.center.au.entity.Org;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.center.au.entity.UserVerify;
import com.hb.core.pojo.enums.UserStatusEnum;
import com.hb.trade.client.center.OrgClient;
import com.hb.trade.client.center.UserClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.web.bind.annotation.*;

/**
 * 用户绑定第三方ca相关
 */
@Slf4j
@Version(1.0)
@Api(tags = {"用户绑定CA中招等第三方相关接口"})
@RequestMapping("/{version}")
@RestController
public class ApiUserVerifyController {
    protected final UserClient userClient;
    protected final OrgClient orgClient;

    public ApiUserVerifyController(UserClient userClient,
                                   OrgClient orgClient) {
        this.userClient = userClient;
        this.orgClient = orgClient;
    }

    /**
     * 绑定CA
     *
     * @param zappUserDTO
     * @date 2022-3-25 09:01:11
     * @author ljs
     */
    @ApiOperation(value = "绑定中招APP", notes = "绑定中招APP")
    @PostMapping("/user/userBindZapp")
    public ResponseDto userBindZapp(@RequestBody ZappUserDTO zappUserDTO){

        if (zappUserDTO.getRoleSign() == null){
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM);
        }
        // 获取用户信息
        Message<UserDTO> userMessage = userClient.getByUsername(zappUserDTO.getUserName());
        UserDTO userDTO = userMessage.getData();
        if (userDTO == null){
            return ResultUtil.fail(MsgEnum.USERNAME_NOT_FOUND);
        }
        if (!userDTO.getUserStatus().equals(UserStatusEnum.APPROVED.getCode())){
            return ResultUtil.fail("该用户尚未通过审核！");
        }

        // 更新企业信息
        Message<OrgDTO> orgDTOMessage = orgClient.getOrgById(userDTO.getOrgId());
        if (orgDTOMessage.getData()==null){
            return ResultUtil.fail("企业信息不存在！");
        }
        // 判断中招的企业信息
        OrgDTO orgDTO = orgDTOMessage.getData();
        Org org = zappUserDTO.getOrg();
        // 如果企业不是总公司则查询总公司信息 2022年4月28日 产品说分公司跟总公司用的一套企业信息
        if (!orgDTO.getParentId().equals(0L)){
            Message<OrgDTO> headOfficeMessage = orgClient.getHeadOffice(orgDTO.getId());
            orgDTO = headOfficeMessage.getData();
        }
        if (orgDTO.getOrgName().equals(org.getOrgName()) && orgDTO.getCreditCode().equals(org.getCreditCode())){
            org.setId(orgDTO.getId());
            orgClient.saveOrg(org.to(OrgDTO.class));
        }else {
            return ResultUtil.fail("中招企业信息与用户企业信息不符！");
        }


        if(zappUserDTO.getFastLoginFlag() == null){
            // ----------------start 扫码签章认证-----------------
            UserVerify userVerify = new UserVerify();
            userVerify.setUserId(userDTO.getId());
            userVerify.setVerifyType(2);
            userVerify.setAuditStatus(1);
            userVerify.setVerifyCode(zappUserDTO.getUnifiedTransactionCode());
            userVerify.setBackInfo(zappUserDTO.getUser().getBackInfo());
            // 保存
            Message<Boolean> result = userClient.saveVerifyByZapp(userVerify);
            userClient.updateUser(zappUserDTO.getUser());
            return ResultUtil.msg(result);
            // ----------------end 扫码签章认证-----------------
        }else if(zappUserDTO.getFastLoginFlag().equals(3) || zappUserDTO.getFastLoginFlag().equals(1)){
            // ----------------start 企业认证-----------------
            boolean fastLoginFlag = false;
            String msg = "";
            // 如果中招信息和个人信息相同
            if(userDTO.getPhone().equals(zappUserDTO.getTelephoneNum()) && userDTO.getUnifiedTransactionCode()==null){
                fastLoginFlag = true;
                User user = userClient.getUserByUnifiedTransactionCodeAndRoleSign(zappUserDTO);
                if (user!=null && !user.getId().equals(userDTO.getId())){
                    msg = "该中招已经绑定过其他账号";
                    fastLoginFlag = false;
                }
            }else {
                if (userDTO.getUnifiedTransactionCode()!=null){
                    msg = "该账号已经绑定过中招";
                }else {
                    msg = "手机号与中招信息不符";
                }
            }
            UserVerify userVerify = new UserVerify();
            userVerify.setVerifyType(2);
            userVerify.setAuditStatus(1);
            userVerify.setVerifyCode(zappUserDTO.getUnifiedTransactionCode());
            userVerify.setBackInfo(zappUserDTO.getUser().getBackInfo());
            if (!fastLoginFlag && zappUserDTO.getFastLoginFlag().equals(1)){
                return ResultUtil.fail(msg);
            }

            if (fastLoginFlag){
                userVerify.setUserId(userDTO.getId());
                // 更新用户信息
                UserDTO userInfoDTO = zappUserDTO.getUser();
                userInfoDTO.setId(userDTO.getId());
                userInfoDTO.setUnifiedTransactionCode(zappUserDTO.getUnifiedTransactionCode());
                userClient.updateUser(userInfoDTO);
            }
            // 保存
            Message<Boolean> result = userClient.saveVerifyByZapp(userVerify);
            userClient.updateUser(zappUserDTO.getUser());
            return ResultUtil.msg(result);
            // ----------------end 企业认证-----------------
        }else{
            return ResultUtil.FAIL;
        }
    }

    /**
     * 判断用户是否绑定了中招
     *
     * @param
     * @date 2022-4-22
     * @author ljs
     */
    @ApiOperation(value = "判断用户是否绑定了中招", notes = "判断用户是否绑定了中招")
    @GetMapping("/user/existUserVerify")
    public ResponseDto<JSONObject> existUserVerify(){
        Long userId = ShiroUtil.getUserId();
        User user = new User();
        user.setId(userId);
        Message<User> userDTOMessage = userClient.getByUserId(userId);
//        Message<UserVerify> verifyMessage = userClient.getUserVerifyByUserId(user);
        JSONObject jsonObject = new JSONObject();
        User user1 = userDTOMessage.getData();
        if (user1!=null && user1.getUnifiedTransactionCode()!=null){
            jsonObject.putOpt("bindFlag", 1);
        }else {
            jsonObject.putOpt("bindFlag", 0);
        }
        return ResultUtil.msg(true, jsonObject);
    }



    /**
     * 判断中招token是否过期
     *
     * @author tian
     * @date 2022-6-16 16:39
     * @return org.fzzn.core.model.msg.ResponseDto
     */
    @ApiOperation(value = "判断中招token是否过期", notes = "绑定中招APP")
    @GetMapping("/user/judgeZZToken")
    public ResponseDto judgeZZToken() {
        // 当前登录人id
        Long userId = ShiroUtil.getUserId();
        // 获取中招token是否失效（有效期10天）
        Message<Boolean> verifyInfo = userClient.judgeZZToken(userId);
        return ResultUtil.msg(verifyInfo);
    }



    /**
     * 更新中招信息（解密时用户token过期）
     *
     * @author tian
     * @date 2022-6-16 17:51
     * @param zappUserDTO
     * @return org.fzzn.core.model.msg.ResponseDto
     */
    @ApiOperation(value = "更新中招信息（解密时用户token过期）", notes = "绑定中招APP")
    @PostMapping("/user/updateUserVerify")
    public ResponseDto updateUserVerify(@RequestBody ZappUserDTO zappUserDTO) {
        Long userId = ShiroUtil.getUserId();
        UserVerify userVerify = new UserVerify();
        userVerify.setUserId(userId);
        userVerify.setVerifyType(2);
        userVerify.setAuditStatus(1);
        userVerify.setVerifyCode(zappUserDTO.getUnifiedTransactionCode());
        userVerify.setBackInfo(zappUserDTO.getUser().getBackInfo());
        Message<Boolean> booleanMessage = userClient.saveVerifyByZapp(userVerify);
        return ResultUtil.msg(booleanMessage);
    }
}
